<!--
 * @Author: 清酒吖
 * @Date: 2022-01-17 16:43:22
 * @Email:  
 * @LastEditors:  
 * @LastEditTime: 2022-02-07 15:06:52
 * @Description: 
 * @version: x 1.0
-->
 <template>
  <div class="app-container">
    <!-- 查询条件 -->
    <template>
      <el-form :inline="true" :model="brand" class="demo-form-inline">
        <el-form-item label="品牌名称">
          <el-input
            v-model="brand.name"
            placeholder="请输入产品品牌名称..."
            clearable
            @clear="selectBrand()"
          ></el-input>
        </el-form-item>

        <el-form-item label="展示状态">
          <el-select
            v-model="brand.showStatus"
            clearable
            @clear="selectBrand()"
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            round
            icon="el-icon-zoom-in"
            @click="
              pageNum = 1;
              selectBrand();
            "
            >查询</el-button
          >

          <el-button
            type="success"
            icon="el-icon-circle-plus-outline"
            round
            @click="toAdd()"
            >添加</el-button
          >

          <el-button
            type="danger"
            icon="el-icon-circle-close"
            @click="delBatch()"
            round
            >批量删除</el-button
          >
        </el-form-item>
      </el-form>
    </template>

    <!-- 渲染查询的记录在表格中 -->
    <el-table
      :data="brandList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>

      <el-table-column prop="id" label="ID" align="center" width="">
      </el-table-column>

      <el-table-column prop="name" label="品牌名称" align="center" width="180">
      </el-table-column>

      <el-table-column prop="firstLetter" align="center" label="首字母">
      </el-table-column>

      <el-table-column prop="sort" label="排序" align="center">
        <template slot-scope="scope">
          <div>
            {{ scope.row.sort | nullFormat }}
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="" label="是否展示" align="center" width="180">
        <template slot-scope="scope">
          <div>
            <el-switch
              v-model="scope.row.showStatus"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
              @change="changeStatus(scope.row)"
            >
            </el-switch>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        prop="productCount"
        label="产品数量"
        align="center"
        width="180"
      >
        <template slot-scope="scope">
          <div>
            {{ scope.row.productCount | nullFormat }}
          </div>
        </template>
      </el-table-column>

      <el-table-column
        prop="productCommentCount"
        label="产品评论数量"
        align="center"
        width="180"
      >
        <template slot-scope="scope">
          <div>
            {{ scope.row.productCommentCount | nullFormat }}
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="" label="品牌logo" align="center" width="180">
        <template slot-scope="scope">
          <div>
            <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.logo"
              :fit="fit"
            >
            </el-image>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            circle
            @click="toUpdate(scope.row)"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            @click="remove(scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <br />
    <!-- 分页 -->
    <el-pagination
      style="float: right"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 表单 -->
    <template>
      <el-dialog :title="titleInfo" :visible.sync="dialogFormVisible">
        <el-form
          :model="brandFrom"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="品牌名称" prop="name">
            <el-input v-model="brandFrom.name"></el-input>
          </el-form-item>

          <el-form-item label="品牌首字母" prop="firstLetter">
            <el-input v-model="brandFrom.firstLetter"></el-input>
          </el-form-item>

          <!-- 是否展示 -->
          <el-form-item
            label="是否展示"
            prop="showStatus"
            v-if="showStatusVisible"
          >
            <el-select
              v-model="brandFrom.showStatus"
              placeholder="请选择是否展示"
            >
              <el-option label="展示" value="1"></el-option>
              <el-option label="隐藏" value="0"></el-option>
            </el-select>
          </el-form-item>

          <!-- 图片上传 -->
          <el-form-item label="Logo" prop="logo">
            <el-upload
              :headers="headers"
              ref="brandImg"
              list-type="picture"
              action="http://localhost:9527/upload/img"
              :show-file-list="true"
              :limit="1"
              :auto-upload="true"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :on-remove="handleRemove"
            >
              <img v-if="dialogImageUrl" :src="dialogImageUrl" class="avatar" />

              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <!-- <el-upload
                            ref="brandImg"
                            action="http://localhost:9527/upload/img"
                            list-type="picture-card"
                            :limit="1"
                            :on-success="handleAvatarSuccess"
                            :auto-upload="true">
                                <i slot="default" class="el-icon-plus"></i>
                                <div slot="file" slot-scope="{file}">
                                <img
                                    class="el-upload-list__item-thumbnail"
                                    :src="dialogImageUrl" alt=""
                                >
                                <span class="el-upload-list__item-actions">
                                    <span
                                    class="el-upload-list__item-preview"
                                    @click="handlePictureCardPreview(file)"
                                    >
                                    <i class="el-icon-zoom-in"></i>
                                    </span>
                                    <span
                                    v-if="!disabled"
                                    class="el-upload-list__item-delete"
                                    @click="handleDownload(file)"
                                    >
                                    <i class="el-icon-download"></i>
                                    </span>
                                    <span
                                    v-if="!disabled"
                                    class="el-upload-list__item-delete"
                                    @click="handleRemove(file)"
                                    >
                                    <i class="el-icon-delete"></i>
                                    </span>
                                </span>
                                </div>
                        </el-upload> -->
            <el-dialog :visible.sync="imgVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            @click="
              dialogFormVisible = false;
              restBrand();
            "
            >取 消</el-button
          >
          <el-button
            type="primary"
            @click="
              
              saveBrand();
            "
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </template>
  </div>
</template>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<script>
import {
  findGoodsBrand,
  addGoodsBrand,
  updateGoodsBrand,
  delGoodsBrand,
} from "@/api/mallGoodsBrand";

export default {
  data() {
    return {
      headers:{ // 图片上传请求头
        "token":localStorage.getItem("token"),
      },
      brand: {}, // * 查询条件
      pageNum: 1, // * 当前页数
      pageSize: 5, // * 当前页记录数
      total: 0, // * 总记录数
      pages: 0, // * 总页数
      brandList: [], // * 查询当前页的记录数
      fit: "fit", // * 图片如何适应容器框
      multipleSelection: [], // * 保存勾选的行记录数
      options: [
        // * 是否展示下拉框
        {
          value: 1,
          label: "展示",
        },
        {
          value: 0,
          label: "隐藏",
        },
      ],
      titleInfo: "",
      brandFrom: {
        showStatus: "0",
      }, // 保存表单数据
      //表单校验规则
      rules: {
        name: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        firstLetter: [
          { required: true, message: "请输入品牌首字母", trigger: "blur" },
          { min: 1, max: 1, message: "长度为1个字符", trigger: "blur" },
        ],
        showStatus: [
          { required: true, message: "请选择活动区域", trigger: "change" },
        ],
        logo: [{ required: true, message: "请上传Logo", trigger: "change" }],
      },
      dialogFormVisible: false, // 对话框显示隐藏状态
      dialogImageUrl: "", //上传图片的路径
      dialogVisible: false, // 会话框显示状态
      showStatusVisible: true,
      ids: [], // 删除商品品牌的id
      imgVisible: false, //
      disabled: false,
    };
  },

  methods: {
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // * 每页显示记录数
    handleSizeChange(pageSizeNow) {
      // -> 监听当前页显示条数的变化
      console.log(pageSizeNow);
      this.pageSize = pageSizeNow;
      this.selectBrand();
    },
    // * 分页
    handleCurrentChange(pageNumNow) {
      //-> 监听当前页的变化
      console.log(pageNumNow);
      this.pageNum = pageNumNow;
      this.selectBrand();
    },
    // * 条件+分页查询
    selectBrand() {
      // -> 与服务器交互
      findGoodsBrand(this.brand, this.pageNum, this.pageSize).then((res) => {
        this.brandList = res.pageList;

        this.pages = res.pages;

        this.total = res.total;

        console.log(this.brandList);
      });
    },
    // * 打开添加会话框
    toAdd() {
      this.dialogFormVisible = true;
      this.brandFrom = { showStatus: "0" };
      this.showStatusVisible = true;
      // -> 清空图片上传记录
      if (this.$refs.brandImg) {
        this.$refs.brandImg.clearFiles();
      }
      this.dialogImageUrl = "";
      this.titleInfo = "添加商品品牌信息";
    },
    // * 文件上传成功之后的回调
    handleAvatarSuccess(response, file, fileBlacklist) {
      console.log("response:" + response);
      console.log("file:" + file);
      console.log("fileBlacklist:" + fileBlacklist);

      this.brandFrom.logo = response.data;
      this.dialogImageUrl = response.data;
    },
    // * 上传之前的钩子
    beforeAvatarUpload() {},
    // 删除图片
    handleRemove(file, fileList) {
      // -> 清空图片上传记录
      if (this.$refs.brandImg) {
        this.$refs.brandImg.clearFiles();
      }
      this.dialogImageUrl = "";
      console.log(file);
      console.log(fileList);
    },
    // * 查看缩略图的钩子函数
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.imgVisible = true;
    },
    // * 打开修改会话框
    toUpdate(info) {
      this.dialogFormVisible = true;
      this.brandFrom = JSON.parse(JSON.stringify(info));
      this.titleInfo = "修改商品品牌信息";
      this.dialogImageUrl = info.logo;
      this.showStatusVisible = false;
    },
    // * 保存商品品牌
    saveBrand() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // > 判断id是否存在:不存在，执行添加操作，存在，执行修改操作
          if (this.brandFrom.id == null || this.brandFrom.id == "") {
            // -> 与服务器交互,调用添加商品品牌接口
            addGoodsBrand(this.brandFrom).then((res) => {
              if (res.success) {
                this.$notify({
                  title: "成功",
                  message: res.msg,
                  type: "success",
                  duration: 3000,
                });
                this.pageNum = 1;
                this.selectBrand();
              } else {
                this.$notify.error({
                  title: "失败",
                  message: res.msg,
                  type: "success",
                  duration: 3000,
                });
              }
            });
          } else {
            this.header = "修改商品品牌信息";
            // -> 与服务器交互，调用修改接口
            updateGoodsBrand(this.brandFrom).then((res) => {
              if (res.success) {
                this.$notify({
                  title: "成功",
                  message: res.msg,
                  type: "success",
                  duration: 3000,
                });
                this.pageNum = 1;
                this.selectBrand();
              } else {
                this.$notify.error({
                  title: "失败",
                  message: res.msg,
                  type: "success",
                  duration: 3000,
                });
              }
            });
          }
          this.dialogFormVisible = false;
        } else {
          this.$message.error('添加失败！！！');
          return false;
        }
      });

      this.brandFrom = {};
    },
    // # 取消表单
    restBrand(formName){
        this.$refs.ruleForm.resetFields();
    },
    // * 修改显示状态
    changeStatus(info) {
      console.log(info);
      this.brandFrom = info;
      // -> 与服务器交互，调用修改接口
      updateGoodsBrand(this.brandFrom).then((res) => {
        if (res.success) {
          this.$notify({
            title: "成功",
            message: res.msg,
            type: "success",
            duration: 3000,
          });
          this.pageNum = 1;
          this.selectBrand();
        } else {
          this.$notify.error({
            title: "失败",
            message: res.msg,
            type: "success",
            duration: 3000,
          });
        }
      });
      this.brandFrom = {};
    },
    // * 删除商品品牌
    remove(info) {
      (this.ids = []), this.ids.push(info.id);
      
      this.$confirm("此操作将永久删除该商品品牌, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // -> 与服务器交互，调用删除方法接口
          delGoodsBrand(this.ids).then((res) => {
            if (res.success) {
              this.$notify({
                title: "成功",
                message: res.msg,
                type: "success",
                duration: 3000,
              });
              this.pageNum = 1;
              this.selectBrand();
            } else {
              this.$notify.error({
                title: "失败",
                message: res.msg,
                type: "success",
                duration: 3000,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // * 批量删除按钮
    delBatch() {
      this.ids = [];
      this.multipleSelection.forEach((item) => {
        this.ids.push(item.id);
      });
      console.log(this.ids);
      this.$confirm("此操作将永久删除该商品品牌, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // -> 与服务器交互，调用删除方法接口
          delGoodsBrand(this.ids).then((res) => {
            if (res.success) {
              this.$notify({
                title: "成功",
                message: res.msg,
                type: "success",
                duration: 3000,
              });
              this.pageNum = 1;
              this.selectBrand();
            } else {
              this.$notify.error({
                title: "失败",
                message: res.msg,
                type: "success",
                duration: 3000,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  created() {
    this.selectBrand();
  },
};
</script>